package com.mall.coupon.server.service.impl;

import com.mall.common.security.utils.SecurityUtils;
import com.mall.coupon.common.domain.domain.Coupon;
import com.mall.coupon.common.domain.domain.SkuCouponMiddle;
import com.mall.coupon.common.domain.domain.UserCouponMiddle;
import com.mall.coupon.server.mapper.CouponMapper;
import com.mall.coupon.server.service.CouponService;
import com.mall.system.common.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @ClassName CouponServiceImpl
 * @Description 描述
 * @Author Qiu Feng
 * @Date 2025/1/13 14:41
 */
@Service
public class CouponServiceImpl implements CouponService {
    @Autowired
    private CouponMapper couponMapper;
//    @Autowired
//    private ThreadPoolExecutor threadPoolExecutor;
// 创建一个固定大小的线程池

    private static final ExecutorService executorService = Executors.newFixedThreadPool(10);



    @Override
    public void userCouponAdd(Integer id) {
        //获取当前登录人
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Long userId = loginUser.getUserid();
        Long userId = 1L;
        //根据couponId查询优惠券信息
        Coupon coupon = couponMapper.selectCouponById(id);
        if (null == coupon){
            throw new RuntimeException("优惠券不存在");
        }
        // 检查用户是否已经领取过该优惠券
        UserCouponMiddle existingUserCoupon = couponMapper.selectUserCouponByUserIdAndCouponId(userId, id);
        if (existingUserCoupon != null) {
            throw new RuntimeException("您已经领取过该优惠券");
        }
        UserCouponMiddle userCouponMiddle = new UserCouponMiddle();
        userCouponMiddle.setCouponId(Long.valueOf(id));
        userCouponMiddle.setUserId(userId);
        userCouponMiddle.setCouponId(Long.valueOf(id));
        userCouponMiddle.setCouponName(coupon.getCouponName());
        userCouponMiddle.setCouponType(coupon.getCouponType());
        userCouponMiddle.setCouponStatus(0);
        couponMapper.userCouponAdd(userCouponMiddle);
    }

    @Override
    public List<UserCouponMiddle> userCouponMiddleList(Integer couponStatus) throws ExecutionException, InterruptedException {
        //获取用户ID
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserid();
        // 创建一个Callable任务
        Callable<List<UserCouponMiddle>> task = () -> couponMapper.userCouponMiddleList(userId, couponStatus);

        // 提交任务到线程池并获取Future对象
        Future<List<UserCouponMiddle>> future = executorService.submit(task);

        // 从Future对象获取结果（这可能会阻塞直到结果可用）
        return future.get();
    }
    // 记住在应用程序关闭时关闭线程池
    public void shutdown() {
        executorService.shutdown();
    }

    @Override
    public void updateUserCouponMiddleStatus(Integer id) {
        couponMapper.updateUserCouponMiddleStatus(id);
    }
    @Override
    public List<Coupon> filteredCoupons(List<Long> skuId) {

        //获取用户ID
//        Long userId = SecurityUtils.getUserId();
        Long userId = 1L;
        List<Coupon> coupons = couponMapper.settlementCouponList(userId);
        if (null == coupons) {
            throw new RuntimeException("优惠券不存在");
        }
        // 使用Stream流过滤优惠券，只保留适用于指定SKU ID的优惠券
        return coupons.stream().filter(coupon -> {
            //判断优惠券类型是否为通用 1==通用
            if (coupon.getUseType() == 1) {
                return true;
            }
            SkuCouponMiddle skuCouponMiddles = couponMapper.selectSkuCouponMiddleList(skuId, coupon.getId());
            //对于类型为2的优惠券，检查是否存在对应的SKU
            boolean hasMatchingSku = skuCouponMiddles != null &&
                    skuCouponMiddles.getCouponId().equals(coupon.getId()) &&
                    skuCouponMiddles.getStatus() == 0; // 根据实际需求调整状态值
            return hasMatchingSku;
        }).collect(Collectors.toList());
    }
}
